package com.xky.ui.module.inventorManagement.delete;


import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 删除销售订单类
 */
public class DeleteInvenTory extends JFrame {
    // 定义确认删除的安全字符串
    private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";

    public DeleteInvenTory() {
        setTitle("删除库存订单");
        setSize(320, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    /**
     * 带参数构造方法，直接打开指定订单ID的删除界面
     * @param orderId 要删除的销售订单ID
     */
    public DeleteInvenTory(int orderId) {
        setTitle("删除库存订单");
        setSize(320, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        // 自动填充订单ID
        JTextField idField = (JTextField) ((JPanel)((JPanel)getContentPane().getComponent(0)).getComponent(1)).getComponent(0);
        idField.setText(String.valueOf(orderId));
        setVisible(true);
    }

    void init() {
        setLayout(new BorderLayout());
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel jLabel = new JLabel("请输入你要删除的商品ID:", SwingConstants.CENTER);
        jLabel.setFont(new Font("黑体", Font.BOLD, 20));
        titlePanel.add(jLabel);
        jPanel.add(titlePanel);

        // 创建输入面板
        JPanel inputPanel = new JPanel();
        JTextField jTextField = new JTextField(20);
        jTextField.setPreferredSize(new Dimension(300, 30));
        inputPanel.add(jTextField);
        jPanel.add(inputPanel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));

        JButton jButton = new JButton("删除");
        jButton.setFont(new Font("黑体", Font.BOLD, 20));
        jButton.setBorderPainted(false);
        jButton.setBackground(Color.PINK);
        jButton.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(jButton);

        JButton jButton1 = new JButton("取消");
        jButton1.setFont(new Font("黑体", Font.BOLD, 20));
        jButton1.setBorderPainted(false);
        jButton1.setBackground(Color.PINK);
        jButton1.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(jButton1);

        jPanel.add(buttonPanel);

        // 创建删除所有销售订单的按钮面板
        JPanel deleteAllPanel = new JPanel();
        JButton deleteAllButton = new JButton("删除所有库存订单");
        deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
        deleteAllButton.setBorderPainted(false);
        deleteAllButton.setBackground(Color.RED);
        deleteAllButton.setForeground(Color.WHITE);
        deleteAllButton.setPreferredSize(new Dimension(200, 30));
        deleteAllPanel.add(deleteAllButton);

        jPanel.add(deleteAllPanel);

        add(jPanel, BorderLayout.CENTER);

        // 单个销售订单删除按钮事件
        jButton.addActionListener(e -> {
            String idText = jTextField.getText().trim();
            System.out.println("你点击了确定按钮！");
            if (idText.isEmpty()) {
                JOptionPane.showMessageDialog(null, "请输入你要删除的商品ID", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                Integer id = Integer.valueOf(idText);
                int i = JOptionPane.showConfirmDialog(null, "你确定要删除该库存订单吗？", "删除提示", JOptionPane.YES_NO_OPTION);
                if (i == JOptionPane.YES_OPTION) {
                    if (orderExists(id)) {
                        deleteSalesOrder(id);
                        JOptionPane.showMessageDialog(null, "该库存订单删除成功！", "成功提示", JOptionPane.INFORMATION_MESSAGE);
                        setVisible(false);
                    } else {
                        JOptionPane.showMessageDialog(null, "找不到该商品ID,删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "请输入有效的数字ID", "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 取消按钮事件
        jButton1.addActionListener(e -> {
            dispose();
        });

        // 删除所有销售订单按钮事件
        deleteAllButton.addActionListener(e -> {
            // 显示警告对话框，要求用户确认
            int option = JOptionPane.showConfirmDialog(
                    null,
                    "警告：此操作将删除所有库存订单信息，且无法恢复！\n确定要继续吗？",
                    "危险操作确认",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE
            );

            if (option == JOptionPane.YES_OPTION) {
                // 创建输入对话框，要求用户输入安全确认码
                JPanel confirmPanel = new JPanel();
                confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
                confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));

                JLabel instructionLabel = new JLabel("为确保安全，请输入以下确认码：");
                instructionLabel.setForeground(Color.RED);
                instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(instructionLabel);
                confirmPanel.add(Box.createVerticalStrut(10));

                // 使用JTextField显示确认码，允许选择和复制
                JTextField codeField = new JTextField(CONFIRM_CODE);
                codeField.setEditable(false);
                codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
                codeField.setBackground(new Color(240, 240, 240));
                codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(codeField);

                // 添加复制按钮
                JButton copyButton = new JButton("复制确认码");
                copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
                copyButton.addActionListener(evt -> {
                    StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    clipboard.setContents(stringSelection, null);
                });
                confirmPanel.add(Box.createVerticalStrut(5));
                confirmPanel.add(copyButton);
                confirmPanel.add(Box.createVerticalStrut(15));

                JLabel inputLabel = new JLabel("请在下方输入确认码：");
                inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(inputLabel);
                confirmPanel.add(Box.createVerticalStrut(5));

                JTextField confirmField = new JTextField(20);
                confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(confirmField);
                confirmPanel.add(Box.createVerticalStrut(10));

                JLabel warningLabel = new JLabel("请注意：此操作不可撤销！");
                warningLabel.setForeground(Color.RED);
                warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(warningLabel);

                int result = JOptionPane.showConfirmDialog(
                        null,
                        confirmPanel,
                        "安全确认",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.WARNING_MESSAGE
                );

                // 如果用户点击确定，检查输入的确认码是否正确
                if (result == JOptionPane.OK_OPTION) {
                    String userInput = confirmField.getText().trim();

                    if (CONFIRM_CODE.equals(userInput)) {
                        // 执行删除所有销售订单的操作
                        if (deleteAllSalesOrders()) {
                            JOptionPane.showMessageDialog(
                                    null,
                                    "所有库存订单已成功删除！",
                                    "操作成功",
                                    JOptionPane.INFORMATION_MESSAGE
                            );
                            dispose();
                        } else {
                            JOptionPane.showMessageDialog(
                                    null,
                                    "删除所有库存订单失败",
                                    "操作失败",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        }
                    } else {
                        JOptionPane.showMessageDialog(
                                null,
                                "确认码输入错误，操作已取消！",
                                "验证失败",
                                JOptionPane.ERROR_MESSAGE
                        );
                    }
                }
            }
        });
    }

    /**
     * 检查商品ID是否存在
     * @param id 商品ID
     * @return 是否存在
     */
    private boolean orderExists(int id) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT COUNT(*) FROM inventory WHERE product_id = ?");
            preparedStatement.setInt(1, id);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                return resultSet.getInt(1) > 0;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    /**
     * 删除单个商品订单
     * @param id 商品ID
     * @return 是否删除成功
     */
    public boolean deleteSalesOrder(Integer id) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("DELETE FROM inventory WHERE product_id = ?");
            preparedStatement.setInt(1, id);
            int rows = preparedStatement.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    /**
     * 删除所有库存订单
     * @return 是否删除成功
     */
    public boolean deleteAllSalesOrders() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("DELETE FROM inventory");
            return true; // 即使没有记录被删除也算成功
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(DeleteInvenTory::new);
    }
}
